package com.milo.algorithm.sort;

import com.alibaba.fastjson.JSON;

import java.util.Arrays;

/**
 * @author: Milogenius
 * @create: 2019-07-02 17:51
 * @description: 选择排序
 **/
public class SelectionSort {

    public int[] sort(int[] sourceArray){
        //对array进行拷贝,不改变参数内容
        int[] array = Arrays.copyOf(sourceArray, sourceArray.length);
        //总共要进行n-1轮比较
        for (int i = 0; i < array.length; i++) {
            int min = i;
            //每轮需要比较的次数n-i
            for (int j = i+1; j <array.length ; j++) {
                if (array[j]<array[min]) {
                    min=j;
                }
            }
            //将找到的最小值和i所在的位置互换
            if (i != min) {
                int tmp = array[i];
                array[i] = array[min];
                array[min] = tmp;
            }
            
        }
        return array;
    }

    public static void main(String[] args) {
        int[] arr = new int[]{3,44,38,5,47,15,36,26,27,2,46,4,19,50,48};
        SelectionSort selectionSort = new SelectionSort();
        int[] sort = selectionSort.sort(arr);
        System.out.println("排序后的数组顺序:"+ JSON.toJSONString(sort));
    }
}
